﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Global;
using Clipper.ResultAndCurve;
using System.Drawing.Printing;
using ClipperBaseUI.Chart;
using System.Collections.ObjectModel;
using Clipper.BLL;
using System.Data;
using Clipper.Model.DataBaseModel;
using Clipper.ClipperWindow;
using static Clipper.ClipperUserControl.UserWorkSheet;

namespace Clipper.ClipperUserControl
{
    /// <summary>
    /// UserStandardInfo.xaml 的交互逻辑
    /// </summary>
    public partial class UserStandardInfo : UserControl
    {
        #region 变量

        StandardCurveData standardCurve = null;//标准曲线
        BLL.DataBaseBLL.StandardCurveData standardBll = new BLL.DataBaseBLL.StandardCurveData();  //业务逻辑层

        StandardInfo mStandardinfoBll = new StandardInfo();//标定信息查询
        Model.StandardInfo mStandardInfoModel;

        BLL.DetectItems detectModel = new DetectItems();

        System.Timers.Timer changeBton = new System.Timers.Timer();
        #endregion
        #region 初始化
        public UserStandardInfo()
        {
            InitializeComponent();

            changeBton.Elapsed += new System.Timers.ElapsedEventHandler((ss, ee) =>
            {
                TimerFunc func = new TimerFunc(UpdateStatus);
                Dispatcher.Invoke(func, new Object[] { });

                changeBton.Close();

            });
            changeBton.Interval = 200;

            button2.IsEnabled = false; //此处代表button2 不能点击
            //button3.IsEnabled = false;
            //button4.IsEnabled = false;
        }
        public void DataBind()
        {
            if (DataContext == null)
            {
                detectItemSet1.DataBind();
                DataContext = ServiceProvider.StandardCurveVM;
            }
        }
        private void ChartArea_Loaded(object sender, RoutedEventArgs e)
        {

            //chartCurve.AxisX = new Axis(chartCurve, AxisTypeName.X);
            //chartCurve.AxisY = new Axis(chartCurve, AxisTypeName.Y);
            //chartCurve.AxisX.MaxValue = standardCurve.Concentration1; //x轴最大值
            //chartCurve.AxisX.MinValue = standardCurve.Concentration5;//x轴最小值
            //chartCurve.AxisX.StepCount = 100;
            //chartCurve.AxisY.MaxValue = standardCurve.DetectResult1;
            //chartCurve.AxisY.MinValue = standardCurve.DetectResult5;
            //chartCurve.AxisY.StepCount = 100;
            //chartCurve.CreateCoordinate();
            //CurveSeries series = new CurveSeries("series1", chartCurve);
            //chartCurve.SeriesCollection.Add(series);
            //for (double i = 1; i <= 1000; i += 100)
            //{
            //    series.DataPoint.Add(new Point(i, i));
            //}
            //for (double i = 1; i <= 1000; i++)
            //{
            //    series.LinePoint.Add(new Point(i, i));
            //}
            //chartCurve.SeriesCollection[0].ShowCurve();


            //ServiceProvider.StandardCurveVM.CurrentCurve.Add(new Model.CurvePoint()
            //{
            //    ChromeValue = 100,
            //    LightValue = 100,
            //    PointName = "标定1"
            //});
            //chartCurve.AxisX = new Axis(chartCurve, AxisTypeName.X);
            //chartCurve.AxisY = new Axis(chartCurve, AxisTypeName.Y);
            //chartCurve.AxisX.MaxValue = 1000;
            //chartCurve.AxisX.MinValue = 0;
            //chartCurve.AxisX.StepCount = 10;
            //chartCurve.AxisY.MaxValue = 1000;
            //chartCurve.AxisY.MinValue = 0;
            //chartCurve.AxisY.StepCount = 10;
            //chartCurve.CreateCoordinate();
            //CurveSeries series = new CurveSeries("series1", chartCurve);
            //chartCurve.SeriesCollection.Add(series);

            //for (double i = 1; i <= 1000; i += 100)
            //{
            //    series.DataPoint.Add(new Point(i, i));
            //}
            //for (double i = 1; i <= 1000; i++)
            //{
            //    series.LinePoint.Add(new Point(i, i));
            //}
            //chartCurve.SeriesCollection[0].ShowCurve();

        }
        #endregion

        //保存曲线
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            chartCurve.AxisX = new Axis(chartCurve, AxisTypeName.X);
            chartCurve.AxisY = new Axis(chartCurve, AxisTypeName.Y);
            chartCurve.AxisX.MaxValue = 200;
            chartCurve.AxisX.MinValue = 0;
            chartCurve.AxisX.StepCount = 10;
            chartCurve.AxisY.MaxValue = 200000;
            chartCurve.AxisY.MinValue = 0;
            chartCurve.AxisY.StepCount = 10;
            chartCurve.CreateCoordinate();
            Series series = new Series("series1", chartCurve);
            chartCurve.SeriesCollection.Add(series);
            //chart1.SeriesCollection[0].ShowData(new Point(10, 100));

            //CurveFitting.CurveContext ff = new CurveFitting.CurveContext();
            double[] x = new double[] { 0, 0.1, 2, 25, 100, 200 };
            DetectResult bll = new DetectResult();
            DataSet ds = bll.GetStardList();
            //double[] y = new double[] { 189, 734, 5738, 43141, 121070, 197717 };
            //double[] y = new double[] { 1035, 1817, 5470, 29293, 115969, 151235 };
            //double[] y = new double[] { 2048, 3718, 6017, 33090, 117334, 144411 };
            //double[] y = new double[] { 2053, 3002, 7213, 31557, 120840, 149298 };

            //double[] y = new double[] { 1133, 1291, 4094, 23796, 127182, 139352 };
            //double[] y = new double[] { 1544, 1797, 5323, 28928, 141742, 155337 };
            double[] y = new double[] { 148, 329, 2807, 24136, 104747, 142877 };

            //double[] y = new double[6];
            //int i = 5;
            //foreach (DataRow row in ds.Tables[0].Rows)
            //{
            //    y[i] = double.Parse(row[9].ToString());
            //    i--;
            //}

            double[] yout = new double[200];
            Array xArray = x;
            Array yArray = y;
            Array youtArray = yout;
            //double db = ff.Fittings(2, 6, ref xArray, ref yArray, ref youtArray, true);
            chartCurve.SeriesCollection[0].ShowData(youtArray);
        }
        //打印
        private void btnPrint_Click(object sender, RoutedEventArgs e)
        {
            PrintDialog printDialog = new PrintDialog();
            printDialog.PageRangeSelection = PageRangeSelection.AllPages;
            printDialog.UserPageRangeEnabled = true;
            if (printDialog.ShowDialog() == true)
            {
                //grid.Visibility = Visibility.Hidden;
                printRec.LayoutTransform = new ScaleTransform(1, 1);
                int pageMargin = 5;
                Size pageSize = new Size(printDialog.PrintableAreaWidth - pageMargin * 2, printDialog.PrintableAreaHeight
                    - pageMargin * 2);
                printRec.Measure(pageSize);
                printRec.Arrange(new Rect(pageMargin, pageMargin, pageSize.Width, pageSize.Height));
                printDialog.PrintVisual(printRec, "Print Test");
                printRec.LayoutTransform = null;
                //grid.Visibility = Visibility.Visible;

                //printDialog.PrintVisual(printRec, "Print Test");
            }
        }
        //历史曲线
        private void btnHistory_Click(object sender, RoutedEventArgs e)
        {
            ShowCurve();
            //WinHistoryCurve win = WindowFactory.CreateInstance<WinHistoryCurve>();
            //win.ShowDialog();
        }

        //更改标签化
        public void UpdateStatus()
        {
            detectItemSet1.lsvrelase();
        }

        //切换曲线
        private void detectItemSet1_SelectionChangedEvent(object sender, SelectionChangedEventArgs e)
        {
            //WinSelectDisplay win = new WinSelectDisplay(); //弹框进行选择性的进行展示结果
            //win.ShowDialog();
            Model.DetectItems demodel = detectModel.GetModel(detectItemSet1.CurrentItem.detectItem);
            if (demodel.DetectVarietyID == 1)
            {
                ServiceProvider.Monitor.WinStandCurveSelectEnum = Model.EnumModel.WinStandCurveSelectEnum.LINEVALUE;

            }
            else if (demodel.DetectVarietyID == 2)
            {
                ServiceProvider.Monitor.WinStandCurveSelectEnum = Model.EnumModel.WinStandCurveSelectEnum.ORDINARYLINEVALUE;
            }
            


            changeBton.Start();//启动按钮进行工作

            // lblCalculationMethod.Content = detectItemSet1.CurrentItem.FittingApproachInfo.name;
            lblItemShort.Content = detectItemSet1.CurrentItem.detectItem;
            lblStandardItem.Content = detectItemSet1.CurrentItem.name;

            flushStandardCurve(detectItemSet1.CurrentItem.detectItem); //展示标准曲线

            #region  flushStandardCurve（str） 方法里包含的内容

            //standardCurve = standardBll.GetModel(detectItemSet1.CurrentItem.detectItem);  //获取对象

            //if (standardCurve == null)  //选择当前选择的选项    如果为空返回
            //{
            //    return;
            //}
            ////List<double> concentrationList = new List<double>();  //浓度集合            
            //List<double> concentrationList = ServiceProvider.Monitor.GetConcentrationList(standardCurve);  //浓度集合            
            //List<double> detectResultList = ServiceProvider.Monitor.GetDetectResultList(standardCurve); //检测结果集合

            //#region 获取浓度和检测结果

            ////if (standardCurve.Concentration1 != 0)
            ////{

            ////    concentrationList.Add(standardCurve.Concentration1);
            ////}
            ////if (standardCurve.Concentration2 != 0)
            ////{
            ////    concentrationList.Add(standardCurve.Concentration2);

            ////}
            ////if (standardCurve.Concentration3 != 0)
            ////{

            ////    concentrationList.Add(standardCurve.Concentration3);
            ////}
            ////if (standardCurve.Concentration4 != 0)
            ////{

            ////    concentrationList.Add(standardCurve.Concentration4);
            ////}
            ////if (standardCurve.Concentration5 != 0)
            ////{
            ////    concentrationList.Add(standardCurve.Concentration5);
            ////}
            ////if (standardCurve.Concentration6 != 0)
            ////{
            ////    concentrationList.Add(standardCurve.Concentration6);
            ////}

            ////List<double> detectResultList = new List<double>(); //检测结果集合
            ////if (standardCurve.DetectResult1 != 0)
            ////{
            ////    detectResultList.Add(standardCurve.DetectResult1);
            ////}
            ////if (standardCurve.DetectResult2 != 0)
            ////{
            ////    detectResultList.Add(standardCurve.DetectResult2);
            ////}
            ////if (standardCurve.DetectResult3 != 0)
            ////{
            ////    detectResultList.Add(standardCurve.DetectResult3);
            ////}
            ////if (standardCurve.DetectResult4 != 0)
            ////{
            ////    detectResultList.Add(standardCurve.DetectResult4);
            ////}
            ////if (standardCurve.DetectResult5 != 0)
            ////{
            ////    detectResultList.Add(standardCurve.DetectResult5);
            ////}
            ////if (standardCurve.DetectResult6 != 0)
            ////{
            ////    detectResultList.Add(standardCurve.DetectResult6);
            ////}
            //#endregion

            //chartCurve.ClearDataArea();

            ////标准曲线的画法
            //chartCurve.AxisX = new Axis(chartCurve, AxisTypeName.X);
            //chartCurve.AxisY = new Axis(chartCurve, AxisTypeName.Y);
            //chartCurve.AxisX.MaxValue = concentrationList.Max();  //x轴最大值
            //chartCurve.AxisX.MinValue = concentrationList.Min(); //x轴最小值

            //chartCurve.AxisX.StepCount = 10;
            //chartCurve.AxisY.MaxValue = detectResultList.Max();
            //chartCurve.AxisY.MinValue = detectResultList.Min();
            //chartCurve.AxisY.StepCount = 10;

            ////判断曲线是普通还是对数
            //if (ServiceProvider.Monitor.WinStandCurveSelectEnum == Model.EnumModel.WinStandCurveSelectEnum.LINEVALUE)
            //{
            //    chartCurve.CoordinateType = Model.CoordinateInfoEnum.LogXLogY;                      //定标相关系数
            //    lblCorrelation.Content = standardCurve.LineValue;  //定标相关系数
            //}
            //else if (ServiceProvider.Monitor.WinStandCurveSelectEnum == Model.EnumModel.WinStandCurveSelectEnum.ORDINARYLINEVALUE)
            //{
            //    chartCurve.CoordinateType = Model.CoordinateInfoEnum.XY;
            //    lblCorrelation.Content = standardCurve.OrdinaryLineValue;                        //定标相关系数
            //}
            //chartCurve.CreateCoordinate();
            //CurveSeries series = new CurveSeries("series1", chartCurve);
            //chartCurve.SeriesCollection.Add(series);


            //ObservableCollection<Point> xyPoint = new ObservableCollection<Point>();

            //for (int i = 0; i < detectResultList.Count; i++)
            //{
            //    Point temp = new Point();
            //    temp.X = concentrationList[i];
            //    temp.Y = detectResultList[i];

            //    xyPoint.Add(temp);
            //}

            ////for (double i = 1; i < concentrationList.Max(); i++)
            ////{
            ////    series.LinePoint.Add(new Point(i, detectResultList.Max() - i));
            ////}

            //chartCurve.SeriesCollection[0].ShowLine(xyPoint);

            //lblStandardCount.Content = concentrationList.Count.ToString();           //定标点数
            //lblStandardDate.Content = standardCurve.FileTime.ToString("yyyy/MM/dd ");//定标时间

            #endregion

            button2.IsEnabled = true;   //让button2恢复点击
            //button3.IsEnabled = true;   //让button3恢复点击
            //button4.IsEnabled = true;   //让button4恢复点击
        }

        private double myR2(List<double> m_x, List<double> m_y)
        {
            double X = 0;
            foreach (double concentration in m_x)
            {
                X += concentration;
            }

            double y = 0;
            foreach (double detectResult in m_y)
            {
                y += detectResult;  //检测结果集合
            }
            double xAverage = X / m_y.Count;
            double yAverage = y / m_y.Count;

            double countResult = 0; //表达式上面的结果
            double reagentGan = 0;  //表达式下面的结果
            double yreagentGan = 0;
            for (int i = 0; i < m_y.Count; i++)
            {
                countResult += (m_x[i] - xAverage) * (m_y[i] - yAverage);
                reagentGan += Math.Pow((m_x[i] - xAverage), 2);
                yreagentGan += Math.Pow((m_y[i] - yAverage), 2);
            }
            return Math.Pow((countResult / Math.Sqrt(reagentGan * yreagentGan)), 2);

            //int r =∑(Xi - X的平均数)(Yi - Y平均数) / 根号下[∑(Xi - X平均数) ^ 2 *∑(Yi - Y平均数) ^ 2]
        }
        /// <summary>
        /// 绘制曲线
        /// </summary>
        private void ShowCurve()
        {
            ServiceProvider.StandardCurveVM.CurrentCurve.Add(new Model.CurvePoint()
            {
                ChromeValue = 100,
                LightValue = 100,
                PointName = "标定1"
            });
            chartCurve.AxisX = new Axis(chartCurve, AxisTypeName.X);
            chartCurve.AxisY = new Axis(chartCurve, AxisTypeName.Y);
            chartCurve.AxisX.MaxValue = 1000;
            chartCurve.AxisX.MinValue = 0;
            chartCurve.AxisX.StepCount = 10;
            chartCurve.AxisY.MaxValue = 1000;
            chartCurve.AxisY.MinValue = 0;
            chartCurve.AxisY.StepCount = 10;
            chartCurve.CreateCoordinate();
            CurveSeries series = new CurveSeries("series1", chartCurve);
            chartCurve.SeriesCollection.Add(series);

            for (double i = 1; i <= 1000; i += 100)
            {
                series.DataPoint.Add(new Point(i, i));
            }
            for (double i = 1; i <= 1000; i++)
            {
                series.LinePoint.Add(new Point(i, i));
            }
            chartCurve.SeriesCollection[0].ShowCurve();

        }

        private void button_Click(object sender, RoutedEventArgs e)
        {
            WinStandardCurveData win = new WinStandardCurveData();
            win.ShowDialog();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            //执行方法操作步骤 弹出操作步骤框
            WinAutoStandardCurveData win = new WinAutoStandardCurveData();
            win.ShowDialog();
        }

        private void chartCurve_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {

        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            if (standardBll.CheckExist(lblItemShort.Content.ToString()))
            {
                StandardCurveData stand = standardBll.GetModel(lblItemShort.Content.ToString());

                WinChangeStandardPoint standPoint = new WinChangeStandardPoint(); //穿件对象
                standPoint.Tag = stand;
                standPoint.ShowDialog();  //标准曲线

                flushStandardCurve(lblItemShort.Content.ToString());//刷新曲线
            }
        }

        public void flushStandardCurve(string strDetectItem)
        {
            standardCurve = standardBll.GetModel(strDetectItem);  //获取对象

            if (standardCurve == null)  //选择当前选择的选项    如果为空返回
            {
                return;
            }
            //List<double> concentrationList = new List<double>();  //浓度集合            
            List<double> concentrationList = ServiceProvider.Monitor.GetConcentrationList(standardCurve);  //浓度集合            
            List<double> detectResultList = ServiceProvider.Monitor.GetDetectResultList(standardCurve); //检测结果集合          

            chartCurve.ClearDataArea();

            //标准曲线的画法
            chartCurve.AxisX = new Axis(chartCurve, AxisTypeName.X);
            chartCurve.AxisY = new Axis(chartCurve, AxisTypeName.Y);
            chartCurve.AxisX.MaxValue = concentrationList.Max();  //x轴最大值
            chartCurve.AxisX.MinValue = concentrationList.Min(); //x轴最小值

            chartCurve.AxisX.StepCount = 10;
            chartCurve.AxisY.MaxValue = detectResultList.Max();
            chartCurve.AxisY.MinValue = detectResultList.Min();
            chartCurve.AxisY.StepCount = 10;

            //判断曲线是普通还是对数
            if (ServiceProvider.Monitor.WinStandCurveSelectEnum == Model.EnumModel.WinStandCurveSelectEnum.LINEVALUE)
            {
                chartCurve.CoordinateType = Model.CoordinateInfoEnum.LogXLogY;                      //定标相关系数
                lblCorrelation.Content = string.Format("{0:N3}", standardCurve.LineValue);  //定标相关系数
                lblCalculationMethod.Content = "对数";
            }
            else if (ServiceProvider.Monitor.WinStandCurveSelectEnum == Model.EnumModel.WinStandCurveSelectEnum.ORDINARYLINEVALUE)
            {
                chartCurve.CoordinateType = Model.CoordinateInfoEnum.XY;

                lblCorrelation.Content = string.Format("{0:N3}", standardCurve.OrdinaryLineValue);  //定标相关系数
                lblCalculationMethod.Content = "实数";
            }

            chartCurve.CreateCoordinate();
            CurveSeries series = new CurveSeries("series1", chartCurve);
            chartCurve.SeriesCollection.Add(series);

            ObservableCollection<Point> xyPoint = new ObservableCollection<Point>();

            for (int i = 0; i < detectResultList.Count; i++)
            {
                Point temp = new Point();
                temp.X = concentrationList[i];
                temp.Y = detectResultList[i];

                xyPoint.Add(temp);
            }

            //for (double i = 1; i < concentrationList.Max(); i++)
            //{
            //    series.LinePoint.Add(new Point(i, detectResultList.Max() - i));
            //}

            chartCurve.SeriesCollection[0].ShowLine(xyPoint);

            lblStandardCount.Content = concentrationList.Count.ToString();           //定标点数
            lblStandardDate.Content = standardCurve.FileTime.ToString("yyyy/MM/dd ");//定标时间
            lblCloseDate.Content = standardCurve.CloseDate;  //产品有效时间
            lblbatchNumber.Content = standardCurve.BatchNumber; //批号

        }
        // BLL.DataBaseBLL.StandardCurveData standard = new BLL.DataBaseBLL.StandardCurveData();
        private void button3_Click(object sender, RoutedEventArgs e)
        {
            //查看有效期和批号
            string detect = lblItemShort.Content.ToString();
            if (standardBll.CheckExist(detect))
            {
                StandardCurveData standardModel = standardBll.GetModel(detect);
                standardModel.IsShow = false;
                WinShowDateAndNum win = new WinShowDateAndNum();
                win.Tag = standardModel;
                win.ShowDialog();

            }
            else
            {
                //弹框提示没有这个检测项
            }
        }

        private void button4_Click(object sender, RoutedEventArgs e)
        {
            //更改产品批号
            string detect = lblItemShort.Content.ToString();
            if (standardBll.CheckExist(detect))
            {
                StandardCurveData standardModel = standardBll.GetModel(detect);
                standardModel.IsShow = true;
                WinShowDateAndNum win = new WinShowDateAndNum();
                win.Tag = standardModel;
                win.ShowDialog();

            }
            else
            {
                //弹框提示没有这个检测项
            }

        }
    }
}
